#include "common.h"

FLASH_TypeDef *flash = FLASH;

void init_flash(void)
{
    flash->ACR = (2 << 0) | (1 << 4);
    while (!(flash->ACR & (1 << 5)))
        ;
    delay_time(0xff);
}

void flash_unlock(void)
{

    flash->KEYR = FLASH_KEY1;
    flash->KEYR = FLASH_KEY2;
}

void flash_lock(void)
{
    flash->CR |= (1 << 7);
}

void flash_clear_flag(void)
{
    flash->SR = (1 << 2) | (1 << 4) | (1 << 5);
}

void flash_erase_page(unsigned int page)
{
    while (flash->SR & (1 << 0))
        ;
    flash->CR |= (1 << 1);
    flash->AR = page;
    flash->CR |= (1 << 6);
    delay_time(0xffff);
    while (flash->SR & (1 << 0))
        ;
    flash->CR &= ~(1 << 1);
}

void flash_write_halfword(unsigned int addr, unsigned short *data, unsigned int halfword_num)
{
    while (flash->SR & (1 << 0))
        ;
    flash->CR |= (1 << 0);
    for (unsigned int i = 0; i < halfword_num; i++) {
        *((volatile unsigned short *)addr) = *data;
        addr += 2;
        data++;
        while (flash->SR & (1 << 0))
            ;
    }
    flash->CR &= ~(1 << 0);
}

void flash_read_halfword(unsigned short *addr, unsigned short *data, unsigned int halfword_num)
{
    for (unsigned int i = 0; i < halfword_num; i++) {
        data[i] = addr[i];
    }
}
